﻿using System;
using System.Reflection;
using Volo.Abp;

namespace Xms.Abp.Authorization;

public static class PermissionsHelper
{
    public static void Check(Type type)
    {
        if (!typeof(IPermissionsConst).IsAssignableFrom(type))
        {
            throw new AbpException($"Type '{type.FullName}' is invalid permission definition type.");
        }
    }
    public static Type GetLocalizationResource(Type type)
    {
        Check(type);
        return type.GetCustomAttribute<PermissionDefinitionAttribute>().LocalizationResource;
    }
    public static string GetDisplayNameKey(Type type, string nameSpace = null, string propertyName = null)
    {
        Check(type);
        return "Permissions:" + (nameSpace.IsNullOrWhiteSpace() ? "" : ("." + nameSpace)) + type.Name.RemovePostFix("Permissions") + (propertyName.IsNullOrWhiteSpace() ? "" : ("." + propertyName)) + ".DisplayName";
    }

    public static string GetTypeName(Type type)
    {
        return type.Name.RemovePostFix("Permissions");
    }

    public static string GetPermissionName(Type type, string propertyName = null)
    {
        Check(type);
        return GetTypeName(type) + (propertyName.IsNullOrWhiteSpace() ? "" : ("." + propertyName));
    }

    public static string GetSubPermissionName(Type type, string nameSpace, string propertyName = null)
    {
        Check(type);
        return nameSpace + "." + GetTypeName(type) + (propertyName.IsNullOrWhiteSpace() ? "" : ("." + propertyName));
    }
}
